package com.teradata.dashboard.ui.activity;

import java.io.File;
import java.io.FileOutputStream;
import java.io.PrintStream;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import com.teradata.dashboard.DashboardApplication;
import com.teradata.dashboard.R;
import com.teradata.dashboard.dialog.CustomDialog;
import com.teradata.dashboard.utils.DialogUtil;
import com.teradata.dashboard.utils.HttpUtil;

import android.annotation.SuppressLint;
import android.app.ActionBar;
import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.graphics.Typeface;
import android.os.Bundle;
import android.view.GestureDetector;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.webkit.WebChromeClient;

import android.widget.Button;
import android.widget.ListView;

import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.EditText;
import android.widget.SimpleAdapter;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.ViewFlipper;

public class KpiDetailActivity extends BaseActivity {
	final String mimeType = "text/html";  
	final String encoding = "utf-8";
	
	
	private GestureDetector ges;
	private ViewFlipper viewFlipper;
	ActionBar actionBar;
	private int menuId = R.menu.kpi_detailmenu;
	private ListView lv;
    JSONObject jsonObj;
    JSONObject data;
    JSONObject jsonObjComments;
    JSONArray commentsData;
    JSONObject comment;
    
    private EditText comment_edit;
	private Button conmit;
	private String categoryId;
	private String kpiGroupId;
	private String kpiNmae;
	private String categoryNmae;
	
/*	private String KPI_VALUE_DISP;
	private String LAST_FREQ_VALUE;
	private String LAST_YEAR_VALUE;
	private String LAST_YEAR_END_VALUE;
	private String */
	
	private String kpiIds;
	
    private String srcKpiBulletinId;
    private String kpiBulletinDetail;
    private String DIM_VALUE_ID1;
    private String DATA_DATE;
    private String FREQ_ID;
    
    private String COLUMN_FILE = "file:///android_asset/html/column.html";
    private String LINE_FILE = "file:///android_asset/html/line.html";
    private String LINE_PIE = "file:///android_asset/html/pie.html";
    
    String categoryNames ;
	String categoryDatas;
	
    CustomDialog dialog1;
    
    @SuppressLint("SetJavaScriptEnabled")  
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
        super.onCreate(savedInstanceState);
        setContentView(R.layout.kpidetail);
        
        Intent intent = getIntent();
        JSONObject data=null;
		try {
			data = new JSONObject(intent.getStringExtra("json"));
		} catch (JSONException e3) {
			// TODO Auto-generated catch block
			e3.printStackTrace();
		}
        kpiIds = intent.getStringExtra("kpiId");
        kpiNmae = intent.getStringExtra("KPI_GROUP_NAME");
        categoryId = intent.getStringExtra("KPI_CATEGORY_ID");
        kpiGroupId = intent.getStringExtra("KPI_GROUP_ID");
        
        try {
	        	((TextView)findViewById(R.id.KPI_VALUE_DISP)).setText(data.getString("KPI_VALUE_DISP"));
	        	((TextView)findViewById(R.id.LAST_FREQ_VALUE)).setText(data.getString("LAST_FREQ_VALUE"));
	        	((TextView)findViewById(R.id.LAST_YEAR_VALUE)).setText(data.getString("LAST_YEAR_VALUE"));
	        	((TextView)findViewById(R.id.LAST_YEAR_END_VALUE)).setText(data.getString("LAST_YEAR_END_VALUE"));
	        	((TextView)findViewById(R.id.EXPECT_VALUE)).setText(data.getString("KPI_VALUE"));
			} catch (JSONException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}

         

        
         
        //System.out.println(kpiNmae);

        /*
         * 通过KpiId获取kpi
         * 
         */
        try {
			jsonObj = queryKpiDetails(kpiIds);
			data=jsonObj.getJSONObject("data");

		} catch (Exception e) {
			// TODO 自动生成的 catch 块
			e.printStackTrace();
		}
        
        getActionBar().setDisplayHomeAsUpEnabled(true);
		getActionBar().setDisplayShowHomeEnabled(false);
		getActionBar().setHomeButtonEnabled(true);
		//getActionBar().setNavigationMode(ActionBar.NAVIGATION_MODE_STANDARD);
		//getActionBar().setDisplayOptions(0, ActionBar.DISPLAY_SHOW_TITLE);
		getActionBar().setTitle(kpiNmae);
		
		//getActionBar().setSubtitle(kpiNmae);
		
       
		/*
		 *获取webview1 
		 * *
		 */
		WebView wv = (WebView) findViewById(R.id.kpiQushiWB);  
		wv.setBackgroundColor(Color.argb(0xff, 0xff, 0xff, 0xff));
        wv.getSettings().setJavaScriptEnabled(true);  
        wv.getSettings().setUseWideViewPort(true);
        wv.getSettings().setSupportZoom(true); 
        wv.getSettings().setBuiltInZoomControls(true);
        wv.getSettings().setLoadWithOverviewMode(true);  
        wv.requestFocus();  
        String content = "<html><head></head><body>sdsfsdf</body></html>";
        write(content);
        
        //wv.loadUrl(COLUMN_FILE);
        try {
			wv.loadData(URLEncoder.encode(content, encoding), mimeType, encoding);
		} catch (UnsupportedEncodingException e2) {
			// TODO 自动生成的 catch 块
			e2.printStackTrace();
		} 
        
        /*
		 *获取webview2
		 * *
		 */
        final WebView paimingwv = (WebView) findViewById(R.id.kpipaimingWB);
        paimingwv.setBackgroundColor(Color.argb(0xff, 0xff, 0xff, 0xff));
        paimingwv.getSettings().setJavaScriptEnabled(true);  
        paimingwv.getSettings().setUseWideViewPort(true);
        paimingwv.getSettings().setSupportZoom(true); 
        paimingwv.getSettings().setBuiltInZoomControls(true);
        paimingwv.getSettings().setLoadWithOverviewMode(true);  
        paimingwv.requestFocus();  
        paimingwv.loadUrl("file:///android_asset/html/line.html");
        
        try {
			JSONObject webView2 = queryWebView("00","00000000","20130131","CDS0020000000",
					"CDS100000000","1","chart0","00");
			 categoryNames = webView2.getString("categoryNames");
			 categoryDatas = webView2.getString("datas");
			
			System.out.println(categoryNames);
			System.out.println(categoryDatas);
		} catch (Exception e2) {
			// TODO 自动生成的 catch 块
			e2.printStackTrace();
		}
        
        paimingwv.setWebViewClient(new WebViewClient() {   
                    
            public void onReceivedError(WebView view, int errorCode, String description, String failingUrl)   
            {                 // Handle the error       
                 
            }             
            
            public void onPageFinish (WebView view, String url){
            	System.out.println("onPageFinish"+url);
            	paimingwv.loadUrl("javascript:showChart()");
            	
            }
            public boolean shouldOverrideUrlLoading(WebView view, String url) 
            {              
                view.loadUrl(url);   
                return true;       
                }      
            });   
        
       // paimingwv.loadUrl("javascript:showChart()");
        /*
		 *获取webview3 
		 * *
		 */
        WebView jiegouwv = (WebView) findViewById(R.id.kpijiegouWB);  
        jiegouwv.setBackgroundColor(Color.argb(0xff, 0xff, 0xff, 0xff));
        jiegouwv.getSettings().setJavaScriptEnabled(true);  
        jiegouwv.getSettings().setUseWideViewPort(true);
        jiegouwv.getSettings().setSupportZoom(true); 
        jiegouwv.getSettings().setBuiltInZoomControls(true);
        jiegouwv.getSettings().setLoadWithOverviewMode(true);  
        jiegouwv.requestFocus();
       // jiegouwv.loadUrl("file:///android_asset/html/pie.html");
        
        
        viewFlipper = (ViewFlipper) findViewById(R.id.details);
		ges = new GestureDetector(KpiDetailActivity.this, onGestureListener);

		/**
		 * 
		 * 获取用户评论
		 * */
		lv = (ListView) findViewById(R.id.commentList);    
		
		try {
			jsonObjComments = queryComments(kpiGroupId, categoryId);
			commentsData = jsonObjComments.getJSONArray("data");
			/*定义一个动态数组*/     
			 ArrayList<HashMap<String, Object>> listItem = 
					 new ArrayList<HashMap<String,     Object>>();
			/*在数组中存放数据*/
			 for(int i=0;i<commentsData.length();i++)  
			        {  
			            HashMap<String, Object> map = new HashMap<String, Object>();  
			            comment = commentsData.getJSONObject(i);
			            
			            map.put("commentImg", R.drawable.ic_launcher);
			            map.put("userName", comment.get("publishUserName"));
			            map.put("position", comment.get("publishUserBranchName"));  
			            map.put("commentTime", comment.get("publishDatetime"));  
			            map.put("commentContent", comment.get("bulletinDetail"));  
			            
			            listItem.add(map);  

			        }
		
		 
		  SimpleAdapter mSimpleAdapter =new SimpleAdapter(this,listItem,               
				 R.layout.commentitems,
				 new String[] {"commentImg"
			 ,"userName", "position", "commentTime", "commentContent"},   
			 new int[] {R.id.commentImg,R.id.userName,R.id.position, R.id.commentTime, R.id.commentContent}  );
		 
		  lv.setAdapter(mSimpleAdapter);//为ListView绑定适配器 lv.setOnItemClickListener(new 
		  
		  lv.setOnItemClickListener(new 
				  OnItemClickListener() {

				              @Override
				              public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
				                      long arg3) {
				               //   setTitle("你点击了第"+arg2+"行");//设置标题栏显示点击的行                
				              }
				          });
				  
		  
		//ActionBar
		actionBar = getActionBar();
		actionBar.setDisplayShowHomeEnabled(true);
		actionBar.setDisplayHomeAsUpEnabled(true);
		actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_LIST);
		
        
		//评论事件
		
	    conmit = (Button) findViewById(R.id.conmit);
	    
	    conmit.setOnClickListener(new OnClickListener(){
        	public void onClick(View v)
        	{
        		//show.setText("");
        		comment_edit = (EditText) findViewById(R.id.comment_edit);
        		kpiBulletinDetail=comment_edit.getText().toString();
					try {
						JSONObject commentResult = postComment(categoryId, kpiGroupId, srcKpiBulletinId, 
								kpiBulletinDetail, DIM_VALUE_ID1, DATA_DATE, FREQ_ID);
						if(commentResult.getString("success").equals("true"))
						{
							//显示评论成功
							comment_edit.setText("");
							dialog1 = new CustomDialog(KpiDetailActivity.this, 180, 180, R.layout.success_dialog, R.style.Theme_dialog);
				            dialog1.show();
				            //dialog1.setCanceledOnTouchOutside(false);
				           
				            Runnable run = new Runnable(){
				            	public void run()
				            	{
				            		try {
				    					Thread.sleep(1000 * 4);
				    					dialog1.dismiss();
				    				} catch (InterruptedException e) {
				    					// TODO 自动生成的 catch 块
				    					e.printStackTrace();
				    				}
				            	}
				            };
				            Thread clock = new Thread(run);
				            clock.start();
							
						}
					} catch (Exception e) {
						// TODO 自动生成的 catch 块
						e.printStackTrace();
					}
					System.out.println("javascript:showChart()");
					//categoryNames = "['a', 'b', 'c', 'd', 'd']";
					
					
					/*
					
					String[] test1 = categoryDatas.split("\",\"");
					
					System.out.println(test1[0]);
					
					System.out.println(Double.parseDouble(test1[0]));
					
					double[] a = new double[test1.length];
					for(int i = 0; i<test1.length; i++)
					{
						a[i] = Double.parseDouble(test1[i]);
						System.out.println(a[i]);
					}
										
					int[] b = {1, 2};*/
					System.out.println("怎么才能进去？？");
					paimingwv.loadUrl("javascript:setData("+categoryDatas+")");
					//paimingwv.loadUrl("javascript:setCategories(['a', 'b', 'c', 'd'])");
					paimingwv.loadUrl("javascript:setCategories("+categoryNames+")");
	
					
					
	        }
	        });
			     
		} catch (Exception e1) {
			// TODO 自动生成的 catch 块
			e1.printStackTrace();
		}	
		
	}
	


	/*
	 * 
	 * 
	 * 写webview文件
	 * 
	 * */
	 private void write(String content)
	{
		try{
			
			//Context.getAssets().open(“html/column.html”) 
			
			File file=new File(COLUMN_FILE);
			if(file.exists())
			{
				System.out.println("删除文件"+ content);
				file.delete();
			}
			else{
				System.out.println("文件不存在");
			}
			
			
			FileOutputStream fos = openFileOutput(COLUMN_FILE, MODE_PRIVATE);
			
			fos.write(content.getBytes());
			fos.close();
		}
		catch(Exception e)
		{
			
		}
	}
	
	
	/*
	 * 
	 * post请求区域
	 * 
	 */
	private JSONObject queryComments(String kpiGroupId, String categoryId)
			throws Exception
		{
			//使用Map封装请求参数
			Map<String, String> map = new HashMap<String, String>();
			map.put("kpiGroupId", kpiGroupId);
			map.put("categoryId", categoryId);
			
			// 定义发送请求的URL
			String url = HttpUtil.BASE_URL + "dashboard/listKpiBulletin.action";
			// 发送请求
			return new JSONObject(HttpUtil.postRequest(url, map));
		}

	private JSONObject queryKpiDetails(String kpiId)
			throws Exception
		{
			//使用Map封装请求参数
			Map<String, String> map = new HashMap<String, String>();
			map.put("kpiId", kpiId);
			
			// 定义发送请求的URL
			String url = HttpUtil.BASE_URL + "dashboard/findKpiById.action";
			// 发送请求
			return new JSONObject(HttpUtil.postRequest(url, map));
		}

		private JSONObject postComment(String categoryId, String kpiGroupId, String srcKpiBulletinId,
								String kpiBulletinDetail, String DIM_VALUE_ID1, String DATA_DATE,
								String FREQ_ID)
			throws Exception
		{
			//使用Map封装请求参数
			Map<String, String> map = new HashMap<String, String>();
			map.put("categoryId", categoryId);
			map.put("kpiGroupId", kpiGroupId);
			map.put("srcKpiBulletinId", srcKpiBulletinId);
			map.put("kpiBulletinDetail", kpiBulletinDetail);

			// 定义发送请求的URL
			String url = HttpUtil.BASE_URL + "dashboard/addBulletin.action";
			// 发送请求
			return new JSONObject(HttpUtil.postRequest(url, map));
		}
	
		private JSONObject postOrder(String kpiIds, 
					String kpiCategoryId, String parKpiGroupId, 
					String userFlag)
				throws Exception
			{
				//使用Map封装请求参数
				Map<String, String> map = new HashMap<String, String>();
				map.put("kpiIds", kpiIds);
				map.put("kpiCategoryId", kpiCategoryId);
				map.put("parKpiGroupId", parKpiGroupId);
				map.put("userFlag", userFlag);
				
				// 定义发送请求的URL
				String url = HttpUtil.BASE_URL + "dashboard/addKpi.action";
				// 发送请求
				return new JSONObject(HttpUtil.postRequest(url, map));
			}
		
		
		private JSONObject queryWebView(String FREQ_ID, String DIM_VALUE_ID1,
						String DATA_DATE, String kpiGroupId,
						String categoryId,
						String chartTypeId,  
						String chartId,
						String analisisTypeId
						 )
				throws Exception
			{
				//使用Map封装请求参数
				Map<String, String> map = new HashMap<String, String>();
				map.put("FREQ_ID", FREQ_ID);
				
				map.put("DIM_VALUE_ID1", DIM_VALUE_ID1);
				map.put("DATA_DATE", DATA_DATE);
				
				map.put("kpiGroupId", kpiGroupId);
				map.put("categoryId", categoryId);
				map.put("chartTypeId", chartTypeId);
				map.put("chartId", chartId);
				map.put("analisisTypeId", analisisTypeId);
				
				// 定义发送请求的URL
				String url = HttpUtil.BASE_URL + "dashboard/getChartData.action";
				// 发送请求
				return new JSONObject(HttpUtil.postRequest(url, map)).getJSONObject("data");
			}

	private GestureDetector.OnGestureListener onGestureListener = 
			new GestureDetector.SimpleOnGestureListener(){
				@Override
				public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX,
						float velocityY) {
					float x = e2.getX() - e1.getX();
					if(x<0)
					{
						leftSide();
					}
					else if(x>0)
					{
						rightSide();
					}
					return true;
				}
				
			};

	public boolean onTouchEvent(MotionEvent event)
			{
				return ges.onTouchEvent(event);
			}
			
	public void leftSide()
			{
				viewFlipper.setInAnimation(this, R.anim.in_from_right);
				viewFlipper.setOutAnimation(this, R.anim.out_to_left);
				
				viewFlipper.showPrevious();
				viewFlipper.stopFlipping();
			}

	public void rightSide()
			{
				viewFlipper.setInAnimation(this, R.anim.in_from_left);
				viewFlipper.setOutAnimation(this, R.anim.out_to_right);
				//
				viewFlipper.showPrevious();
				viewFlipper.stopFlipping();
			}

	
	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		MenuInflater inflater=new MenuInflater(this);
		inflater.inflate(menuId, menu);
		
		/*Typeface iconfont = Typeface.createFromAsset(getAssets(), "fonts/fontawesome-webfont.ttf");
		MenuItem item = menu.findItem(R.id.menu_action_order);
		TextView textView = (TextView)item.getActionView().findViewById(R.id.kpiDetail_acb_order_text);
		textView.setTypeface(iconfont);*/
		
	
		//TextView textView = (TextView)findViewById(R.id.kpiDetail_acb_order_text);
		//textView.setTypeface(iconfont);
		
		return true;
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		//showInfo("select : " + item.getTitle());
		
		ActionBar bar = getActionBar();
		switch(item.getItemId()){
		case R.id.menu_action_order:
			//发送收藏请求
			try {
				JSONObject orderResult = postOrder(kpiIds, categoryId, kpiGroupId, "true");
				if(orderResult.getString("success").equals("true"))
				{
					//收藏成功
					dialog1 = new CustomDialog(KpiDetailActivity.this, 180, 180, R.layout.success_dialog, R.style.Theme_dialog);
		            dialog1.show();
		            //dialog1.setCanceledOnTouchOutside(false);
		           
		            Runnable run = new Runnable(){
		            	public void run()
		            	{
		            		try {
		    					Thread.sleep(1000 * 4);
		    					dialog1.dismiss();
		    				} catch (InterruptedException e) {
		    					// TODO 自动生成的 catch 块
		    					e.printStackTrace();
		    				}
		            	}
		            };
		            Thread clock = new Thread(run);
		            clock.start();
				}
				
			} catch (Exception e) {
				// TODO 自动生成的 catch 块
				e.printStackTrace();
			}
			
			break;
			
		case R.id.menu_action_icon2:
			bar.show();
			break;
		default:
			break;
		}
		
		return super.onOptionsItemSelected(item);
	}
	
}
